<x-app-layout>
    <x-slot name="header">
        <div class="flex justify-between">
            <h2 class="font-semibold text-xl inline-flex items-center text-gray-800 leading-tight md:mr-auto">
                {{$archive->title}}
            </h2>

            @auth
                @can('update', $archive)
                    <a href="{{route($archive->category->slug .'.show', $archive)}}" class="btn-link mr-2">
                        <i class="fa fa-arrow-left mr-1"></i>
                        {{ __('Back') }}
                    </a>
                @endcannot
            @endauth
        </div>
        @if($archive->content)
            <div class="text-sm mt-4">{{$archive->content}}</div>
        @endif
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <livewire:tags.edit :archive="$archive">
            <livewire:archives.edit :archive="$archive">
            <div class="overflow-hidden bg-white shadow sm:rounded-lg p-4" id="files-container">
                <div class="relative" ref="box" :style="{height: containerHeight + 'px'}">
                    <template v-for="(item, index) in boxes">
                        <template v-if="index === boxes.length - 1">
                            <div x-data key="file-btn" class="absolute inline-flex items-center justify-center" :style="{width: item.width + 'px', height: item.height + 'px', top: item.top + 'px', left: item.left + 'px'}">
                                <x-jet-button class="ml-2" @click="openFileSelect">
                                    {{ __('Upload Picture') }}
                                </x-jet-button>
                                <input id="selectBtn" type="file" accept="image/*" style="display:none" ref="input" multiple  @change="selectFiles"/>
                            </div>
                        </template>
                        <template v-else>
                            <div :key="`file-${index}`" class="absolute picture" :style="{width: item.width + 'px', height: item.height + 'px', top: item.top + 'px', left: item.left + 'px'}">
                                <img :src="files[index].file_url" />

                                <div class="absolute inset-0 bg-gray-400 bg-opacity-75 inline-flex items-center justify-center" v-if="files[index].progress < 100 && !files[index].uploadError">
                                    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="30px" height="30px" viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve">
                                        <path opacity="0.2" fill="#FF6700" d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946
      s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634
      c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"></path>
                                        <path fill="#FF6700" d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0
      C22.32,8.481,24.301,9.057,26.013,10.047z" transform="rotate(42.1171 20 20)">
                                            <animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0 20 20" to="360 20 20" dur="0.5s" repeatCount="indefinite"></animateTransform>
                                        </path>
                                    </svg>
                                </div>
                                <div class="absolute inset-0 bg-gray-400 bg-opacity-75 inline-flex items-center justify-center" v-else-if="files[index].uploadError">
                                    <span>@{{files[index].uploadErrorMessage}}</span>
                                </div>
                                <div @click="removeFile(index)" class="cursor-pointer close-icon hidden absolute top-0 right-0 font-weight-bold w-5 h-5 rounded-full text-red-500" style="transform: translate(50%, -50%)">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" class="w-5 h-5" fill="currentColor"><path d="M10 8.586L2.929 1.515 1.515 2.929 8.586 10l-7.071 7.071 1.414 1.414L10 11.414l7.071 7.071 1.414-1.414L11.414 10l7.071-7.071-1.414-1.414L10 8.586z"/></svg>
                                </div>
                            </div>
                        </template>
                    </template>
                </div>
            </div>
        </div>
    </div>
    @push('scripts')

        <script>
                var app = new Vue({
                    el: '#files-container',
                    data() {
                        return {
                            files: @json($archive->files),
                            containerWidth: 0,
                            boxes: [],
                            containerHeight: 0,
                            widowCount: 0,
                        }
                    },
                    mounted() {
                        this.containerWidth = this.$refs.box.offsetWidth
                        this.computePositions()
                    },
                    methods: {
                        openFileSelect() {
                            document.getElementById("selectBtn").click()
                        },

                        computePositions() {
                            const items = this.files.map(file => {
                                return {
                                    id: file.id,
                                    width: file.width,
                                    height: file.height
                                }
                            })
                            items.push({
                                id: 'btn',
                                width: 130,
                                height: 130
                            })

                            var result = justifiedLayout(items, {
                                targetRowHeight: 220,
                                showWidows: true,
                                containerWidth: this.containerWidth,
                                boxSpacing: {
                                    horizontal: 30,
                                    vertical: 30
                                }
                            })
                            this.boxes = result.boxes
                            this.containerHeight = result.containerHeight
                            this.widowCount = result.widowCount
                        },
                        selectFiles(e) {
                            const files = e.target.files

                            for (let i = 0; i < files.length; i++) {
                                const file = files[i];
                                var imageType = /^image\//;

                                if (!imageType.test(file.type)) {
                                    continue;
                                }
                                const img = new Image();
                                img.src = window.URL.createObjectURL(file)
                                const self = this
                                img.onload = function (e) {
                                    const index = self.files.push({
                                        width: img.width,
                                        height: img.height,
                                        file_url: img.src,
                                        isUploading: true,
                                        progress: 0,
                                    })
                                    self.uploadFile(index - 1, file)
                                    if (i === files.length - 1) {
                                        self.computePositions()
                                    }
                                }
                            }
                        },
                        uploadFile(index, file) {
                            const formData = new FormData()
                            formData.append('picture', file)
                            axios.post('/upload/{{$archive->id}}', formData, {
                                headers: {
                                    "Accept": "application/json",
                                },
                                withCredentials: true
                            }).then(res => {
                                this.$set(this.files, index, res.data)
                            }).catch(err => {
                                const message = (err.response && err.response.data && err.response.data.message) ? err.response.data.message : '上传失败'
                                this.$set(this.files[index], 'uploadError', true)
                                this.$set(this.files[index], 'uploadErrorMessage', message)
                            })
                        },
                        removeFile(index) {
                            axios.delete(`/files/${this.files[index].id}`, {
                                headers: {
                                    "Accept": "application/json",
                                },
                                withCredentials: true
                            }).then(res => {
                                this.files.splice(index, 1)
                                this.computePositions()
                            }).catch(err => {

                            })

                        }
                    }
                })
        </script>
    @endpush

</x-app-layout>

